<!-- 修改密码 -->
<template>
  <ql-dialog
    title="修改密码"
    :confirm="confirm"
    @closed="handleDialogClosed"
  >
    <ql-form-list
      ref="form"
      v-model="formData"
      :col="{
        lg: 12,
        xl: 8,
      }"
      :options="options"
    />
  </ql-dialog>
</template>
<script setup>
import { userPwd } from '@/api/common'
import useUserStore from '@/store/user'
const userStore = useUserStore()

const emit = defineEmits(['success'])

const formData = reactive({
  password: '',
  newPassword: '',
  newPasswordAgain: ''
})

const options = reactive([
  {
    label: '旧密码',
    key: 'password',
    type: 'input',
    bind: {
      type: 'password'
    },
    rule: [{
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    }]
  },
  {
    label: '新密码',
    key: 'newPassword',
    type: 'input',
    bind: {
      type: 'password'
    },
    rule: [{
      required: true,
      validator (rule, value, callback) {
        if (!value) return callback(new Error('请输入新密码'))
        if (value === formData.password) {
          callback(new Error('新旧密码不能相同'))
        } else {
          callback()
        }
      }
    }]
  },
  {
    label: '重复新密码',
    key: 'newPasswordAgain',
    type: 'input',
    bind: {
      type: 'password'
    },
    rule: [{
      required: true,
      trigger: 'blur',
      validator (rule, value, callback) {
        if (!value) return callback(new Error('请重复新密码'))
        if (value !== formData.newPassword) {
          callback(new Error('两次密码输入不一致'))
        } else {
          callback()
        }
      }
    }]
  }
])

const userForm = reactive({ ...userStore.form })

const form = ref(null)
const confirm = async () => {
  await form.value?.validate()
  await userPwd(formData)

  // 储存账号密码
  if (userForm.cookie) {
    userForm.password = formData.newPassword
    userStore.setForm(userForm)
  }

  emit('success')
  ElMessage.success('保存成功')
}

const handleDialogClosed = () => {
  form.value?.resetFields() // 清除表单数据
}
</script>

<style scoped lang='scss'>

</style>
